package com.jnshu.security.authentication;

import com.jnshu.pojo.ZuulManage;
import com.jnshu.service.AdminService;
import com.jnshu.tools.MD5Util;
import com.jnshu.tools.binding.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

/**
 * @author xmp
 * @date 2019/8/16 18:10
 */
@Component
@Slf4j
public class CustomAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    CustomizeUserPermission customUserDetailsService;

    @Autowired(required = false)
    AdminService adminService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();
        log.info ("用户输入的名字为：" + name);
        log.info ("用户输入的密码为："+password);
        // userDetails为数据库中查询到的用户信息
        UserDetails userDetails = customUserDetailsService.loadUserByUsername(name);
        log.info("数据库中的用户信息："+ JsonUtil.toJsonString(userDetails));
        ZuulManage manage = adminService.selectManageByName(name);
        log.info("查询出来的账号信息:"+manage);
        boolean verify = MD5Util.getSaltVerifyMD5(password,userDetails.getPassword());
        log.info("校验结果为："+verify);
        if (!verify){
            throw new BadCredentialsException("密码错误");
        }
        return new UsernamePasswordAuthenticationToken(name,password,userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
